import pymysql

# 打开数据库连接  注意文件名不要与pymysql 重名
db = pymysql.connect(host='localhost',
                     user='root',
                     password='root1234',
                     database='pytest',
                     cursorclass=pymysql.cursors.DictCursor)

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# 起始分割线
line_start = lambda action: "".rjust(40, "-") + f'执行sql{action}语句'.ljust(40, "-")
# 结束部分分割线
line_end = lambda: "".rjust(40, "-") + "end".ljust(44, "-")


def insert_db(sql: str):
    global cursor, db
    print(line_start("插入"), "\n", sql, "\n", line_end())
    cursor.execute(sql)
    db.commit()
    print(f'insert_db 插入结果:{cursor.rowcount}')


def update_db(sql: str):
    global cursor, db
    print(line_start("更新"), "\n", sql, "\n", line_end())
    cursor.execute(sql)
    db.commit()
    print(f'update_db 更新操作结果:{cursor.rowcount}')


def del_db(sql: str):
    global cursor, db
    print(line_start("删除"), "\n", sql, "\n", line_end())
    cursor.execute(sql)
    db.commit()
    print(f'del_db 删除操作结果:{cursor.rowcount}')


def find_one(sql: str):
    global cursor
    print(line_start("单条查询"), "\n", sql, "\n", line_end())
    cursor.execute(sql)
    return cursor.fetchone()


def find_list(sql: str):
    global cursor
    print(line_start("查询"), "\n", sql, "\n", line_end())
    cursor.execute(sql)
    return cursor.fetchall()


def close_dblink():
    global cursor
    cursor.close()
    db.close()
